import { insertCart, findCartList, deleteCart } from '@/api/cart'
import { getData, setData } from '@/utils/ls'

const cart = {
  namespaced: true,
  state: () => ({
    cartList: getData('rabbit-cart') || [] // 购物车列表
  }),
  getters: {
    // 总数量 = cartList中每一项的count字段做累加
    allCount (state) {
      return state.cartList.reduce((a, c) => a + c.count, 0)
    },
    // 总钱数 = cartList中每一项的count * price做累加
    allPrice (state) {
      return state.cartList.reduce((a, c) => a + c.count * c.price, 0)
    }
  },
  mutations: {
    // 同步的修改方法
    setCartList (state, cartList) {
      state.cartList = cartList
      // 往本地ls也存一份
      setData('rabbit-cart', cartList)
    }
  },
  actions: {
    async fetchAddCart ({ commit }, { skuId, count }) {
      // 1. 调用加入购物车接口
      await insertCart({ skuId, count })
      // 2. 调用获取购物车最新列表接口
      const res = await findCartList()
      // 3. 提交mutation把购物车列表存入vuex 存入ls
      commit('setCartList', res.result)
    },
    async fetchDelCart ({ commit }, ids) {
      // 1. 删除接口
      await deleteCart(ids)
      // 2. 重新拉取购物车
      const res = await findCartList()
      // 3. 提交mutation把购物车最新的数据存入state
      commit('setCartList', res.result)
    }
  }
}

export default cart
